package com.keyue.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.keyue.common.constant.Constant;
import com.keyue.common.constant.ServerResult;
import com.keyue.common.utils.TransactionHelper;
import com.keyue.domain.dto.BaseDO;
import com.keyue.domain.dto.SystemSettingDO;
import com.keyue.domain.dto.admin.DictionaryDO;
import com.keyue.domain.vo.admin.DictionaryQueryVO;
import com.keyue.domain.vo.admin.DictionaryResultVO;
import com.keyue.domain.vo.admin.DictionaryVO;
import com.keyue.mapper.admin.DictionaryMapper;
import com.keyue.service.admin.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 字典表(Dictionary)表服务实现类
 *
 * @author makejava
 * @since 2023-08-30 17:51:49
 */
@Slf4j
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, DictionaryDO> implements DictionaryService {


    @Resource
    private TransactionHelper transactionHelper;


    /**
     * 通过ID查询单条数据
     * <p>
     * dictionaryQueryVO 主键
     *
     * @return 实例对象
     */
    @Override
    public ServerResult queryById(DictionaryQueryVO dictionaryQueryVO) {
        if (Objects.isNull(dictionaryQueryVO.getId())) {
            return ServerResult.fail("id 不能为空");
        }
        DictionaryDO DictionaryDo = getById(dictionaryQueryVO.getId());
        if (Objects.isNull(DictionaryDo)) {
            return ServerResult.success(null);
        }
        return ServerResult.success(BeanUtil.copyProperties(DictionaryDo, DictionaryVO.class));
    }

    /**
     * 分页查询
     *
     * @param dictionaryQueryVO 筛选条件
     * @return 查询结果
     */
    @Override
    public ServerResult list(DictionaryQueryVO dictionaryQueryVO) {

        return ServerResult.success();
    }

    @Override
    public ServerResult listByPage(DictionaryQueryVO queryVO) {

        LambdaQueryWrapper<DictionaryDO> queryWrapper = buildQueryByParam(queryVO);
        Page page = new Page<>(queryVO.getPage(), queryVO.getPageSize());
        IPage<DictionaryDO> iPage = page(page, queryWrapper);

        Page<DictionaryResultVO> webVOPage = new Page<>();
        List<DictionaryDO> dictionaryDOList = iPage.getRecords();
        if (CollectionUtils.isNotEmpty(dictionaryDOList)) {
            List<DictionaryResultVO> queryVos = dictionaryDOList.stream().map(x -> {
                DictionaryResultVO resultVO = new DictionaryResultVO();
                BeanUtils.copyProperties(x, resultVO);
                return resultVO;
            }).collect(Collectors.toList());
            webVOPage.setRecords(queryVos);
        }
        BeanUtils.copyProperties(page, webVOPage, "records");
        return ServerResult.success(webVOPage);
    }

    /**
     * @param queryVO
     * @return
     */
    private LambdaQueryWrapper<DictionaryDO> buildQueryByParam(DictionaryQueryVO queryVO) {
        return new LambdaQueryWrapper<DictionaryDO>()
                .eq(BaseDO::getEnableFlag, Constant.ENABLE_TEN)
                .like(StringUtils.isNotBlank(queryVO.getDictName()), DictionaryDO::getDictName, queryVO.getDictName())
                .eq(StringUtils.isNotBlank(queryVO.getDictCode()), DictionaryDO::getDictCode, queryVO.getDictCode());
    }

    @Override
    public ServerResult getAll(DictionaryQueryVO dictionaryQueryVO) {
        List<DictionaryDO> dictionaryDOList = list(buildQueryByParam(dictionaryQueryVO));
        if (CollectionUtils.isEmpty(dictionaryDOList)) {
            return ServerResult.success();
        }
        return ServerResult.success(dictionaryDOList.stream().map(x -> {
            DictionaryResultVO resultVO = new DictionaryResultVO();
            BeanUtils.copyProperties(x, resultVO);
            return resultVO;
        }).collect(Collectors.toList()));
    }

    /**
     * 新增数据
     *
     * @param dictionaryVO 实例对象
     * @return 实例对象
     */
    @Override
    public ServerResult add(DictionaryVO dictionaryVO) {
        //todo 校验
        if (Objects.nonNull(dictionaryVO.getId())) {
            dictionaryVO.setId(null);
        }
        DictionaryDO dictionaryDo = BeanUtil.copyProperties(dictionaryVO, DictionaryDO.class);

        transactionHelper.run(() -> {

            save(dictionaryDo);
        });


        return ServerResult.success();
    }

    /**
     * @param dictionaryDo
     * @return
     */
    private List<SystemSettingDO> initSettings(DictionaryDO dictionaryDo) {
        List<SystemSettingDO> systemSettingDOS = new ArrayList<>();
        systemSettingDOS.add(SystemSettingDO.builder()
                .settingCode(dictionaryDo.getDictCode())
                .settingName(dictionaryDo.getDictName())
                .settingValue(dictionaryDo.getDictValue())
                .settingType(Constant.ONE)
                .relationCode("packetPrice")
                .relationName("包装费用")
                .relationValue("0.55")
                .build());
        systemSettingDOS.add(SystemSettingDO.builder()
                .settingCode(dictionaryDo.getDictCode())
                .settingName(dictionaryDo.getDictName())
                .settingValue(dictionaryDo.getDictValue())
                .settingType(Constant.ONE)
                .relationCode("profitRate")
                .relationName("利润率")
                .relationValue("0.3")
                .build());
        return systemSettingDOS;
    }

    /**
     * 修改数据
     *
     * @param dictionaryVO 实例对象
     * @return 实例对象
     */
    @Override
    public ServerResult edit(DictionaryVO dictionaryVO) {
        //todo 校验
        if (Objects.isNull(dictionaryVO.getId())) {
            return ServerResult.fail("id 不能为空");
        }
        DictionaryDO dictionaryDo = BeanUtil.copyProperties(dictionaryVO, DictionaryDO.class);

        updateById(dictionaryDo);

        return ServerResult.success();
    }

    /**
     * 通过主键删除数据
     *
     * @param dictionaryQueryVO 筛选条件
     * @return 是否成功
     */
    @Override
    public ServerResult deleteById(DictionaryQueryVO dictionaryQueryVO) {
        List<Long> ids = dictionaryQueryVO.getIds();
        if (CollUtil.isEmpty(ids)) {
            return ServerResult.fail("ids 参数不能为空");
        }
        List<DictionaryDO> dictionaryList = listByIds(ids);
        if (CollUtil.isEmpty(dictionaryList)) {
            return ServerResult.success();
        }
        //todo 校验是否可以逻辑删除
        LambdaUpdateWrapper<DictionaryDO> updateWrapper = new LambdaUpdateWrapper<DictionaryDO>()
                .in(DictionaryDO::getId, ids)
                .set(DictionaryDO::getEnableFlag, Constant.UNABLE_TWENTY);
        update(updateWrapper);
        return ServerResult.success();
    }
}
